from datetime import datetime
import time

from flask import json, jsonify
from werkzeug.exceptions import HTTPException


class APIException(HTTPException):
    code = 500
    msg = "unknown error"
    error_code = 999
    data = None

    def __init__(self, msg=None, code=None, error_code=None, headers="application/json; charset=utf-8", data=None):
        if msg:
            self.msg = msg
        if code:
            self.code = code
        if error_code:
            self.error_code = error_code
        if data:
            if isinstance(data, object):
                self.data = jsonify(data).json
            self.data = data
        self.headers = headers
        super(APIException, self).__init__(msg, None)

    def get_body(self, environ=None, scope=None, ) -> str:
        data = dict(
            msg=self.msg,
            error_code=self.error_code,
            data=self.data,
            now=int(time.time())
        )
        text = json.dumps(data)
        return text

    def get_headers(self, environ=None, scope=None):
        """Get a list of headers."""
        return [("Content-Type", self.headers)]
